package com.alogic.remote.xscript.auth;

import com.alogic.remote.Request;
import com.alogic.remote.xscript.RequestHandler;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.code.Coder;
import com.anysoft.util.code.CoderFactory;

/**
 *  用户名密码验证
 *  @since 1.6.12.41 [20190902] <br>
 */
public class WithPassword extends RequestHandler {

    protected static String timestampId = "x-alogic-now";
    protected static String pwdId = "x-alogic-pwd";
    protected static String keyId = "x-alogic-app";
    protected static String acGroupKeyId = "x-alogic-ac";
    protected static String acGroup = "app";

    protected Coder des3Coder = null;

    /**
     * 应用id
     */
    protected String $key="";

    /**
     * 密钥
     */
    protected String $keyContent="";

    public WithPassword(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $key = PropertiesConstants.getRaw(p,"key",$key);
        $keyContent = PropertiesConstants.getRaw(p,"keyContent",$keyContent);
        des3Coder = CoderFactory.newCoder("DES3");
    }

    @Override
    protected void onExecute(final Request req, final XsObject root, final XsObject current, final LogicletContext ctx,
                             final ExecuteWatcher watcher) {

        String timestamp = String.valueOf(System.currentTimeMillis());
        String theKey = PropertiesConstants.transform(ctx,$key,"");
        String thePasswd = PropertiesConstants.transform(ctx,$keyContent,"");
        String encryptPwd = des3Coder.encode(thePasswd, theKey + "$" + timestamp);
        req.setHeader(timestampId, timestamp);
        req.setHeader(keyId, theKey);
        req.setHeader(pwdId, encryptPwd);
        req.setHeader(acGroupKeyId, acGroup);
    }
}